using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Threading;
using Common.Utilities.Dispatcher;
using Common.Utilities.DLR;
using FiniteStateMachine;

namespace Workflows.Components.Rules
{
    /// <summary>
    /// execute a rule based on parsed rule instructions
    /// </summary>
    public class RuleWorker : IWorker
    {
        private Thread _WorkerThread;
        private RuleComponentInstruction _Instruction;
        private RuleComponentOutput _Output;
        private RunContext _Context;
        private Guid _TicketID;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }

        /// <summary>
        /// return a handle to worker thread
        /// </summary>
        public Thread WorkerThread
        {
            get { return _WorkerThread; }
        }

        /// <summary>
        /// instruction
        /// </summary>
        public InstructionBase Instruction
        {
            get { return _Instruction; }
        }

        /// <summary>
        /// output
        /// </summary>
        public ResultBase Output
        {
            get { return _Output; }
        }

        /// <summary>
        /// component type so factory can create a worker/agent for
        /// appropriate job
        /// </summary>
        public Type ComponentType
        {
            get { return typeof(RuleComponent); }
        }

        /// <summary>
        /// worker context 
        /// </summary>
        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ticketGuid"></param>
        /// <param name="request"></param>
        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._TicketID = ticketGuid;
            this._Instruction = (RuleComponentInstruction)request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <param name="ticketGuid"></param>
        /// <param name="request"></param>
        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._Context = context;
            this._TicketID = ticketGuid;
            this._Instruction = (RuleComponentInstruction)request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        /// <summary>
        /// sync
        /// </summary>
        public void DoWork()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = Thread.CurrentThread;
            this.EvaluateRule();
        }

        /// <summary>
        /// async
        /// </summary>
        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = new Thread(new ThreadStart(this.EvaluateRule));
            this._WorkerThread.Start();
        }

        /// <summary>
        /// cancel
        /// </summary>
        public void CancelWork()
        {
            if (this._WorkerThread != null && this._WorkerThread.IsAlive)
            {
                this._WorkerThread.Abort();
                this._WorkerThread.Join();

                if (this.WorkerCancelledEvent != null)
                {
                    this.WorkerCancelledEvent(this._TicketID, this.GetType(), this._Instruction);
                }
            }
        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        #region evaluate
        private void EvaluateRule()
        {
            ORMapping<Rule> orm=new ORMapping<Rule>();
            string connStr = ConfigurationManager.ConnectionStrings["Workflow"].ConnectionString;
            Rule rule = orm.GetObjByKey(connStr, this._Instruction.RuleID.ToString());
            RuleParser parser=new RuleParser(rule);
            FiniteStateMachineBase fsm = parser.StateMachine;
            FsmProcessor processor=new FsmProcessor(parser.StateMachineName);
            processor.PushFsm(fsm);
        }
        #endregion

       
    }
}
